import 'dart:math';

import 'package:flutter/cupertino.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';
import 'package:pornhub_app/components/diolog/dialog.dart';
import 'package:pornhub_app/components/diolog/loading/loading_view.dart';
import 'package:pornhub_app/http/api/api.dart';
import 'package:pornhub_app/model/mine/withdraw_config_model.dart';
import 'package:pornhub_app/utils/logger.dart';

import '../../../services/user_service.dart';

class WithdrawPageController extends GetxController {
  final userService = Get.find<UserService>();
  final getArguments = Get.arguments;
  var title = "余额".obs; //(1-余额; 2-金币)

  TextEditingController nameTextEditingController = TextEditingController();
  TextEditingController accountTextEditingController = TextEditingController();
  TextEditingController amountTextEditingController = TextEditingController();
  Rx<WithdrawConfigModel> withdrawConfig = WithdrawConfigModel().obs;

  var payType = 1.obs; //提现方式

  @override
  void onInit() {
    title.value = getArguments['title'] ?? "";
    super.onInit();
    getWithdrawalConfig();
  }

  getWithdrawalConfig() {
    try {
      Api.getWithdrawalConfig().then((response) {
        if (response != null) {
          withdrawConfig.value = response;
        }
      });
    } catch (e) {
      logger.e(e);
    }
  }

  ///申请提现
  applyWithdrawal() async {
    String name = nameTextEditingController.text;
    if (name.trim().isEmpty) {
      showToast("姓名不能为空");
      return;
    }
    String account = accountTextEditingController.text;
    if (account.trim().isEmpty) {
      showToast("账号不能为空");
      return;
    }
    String amount = amountTextEditingController.text;
    if (amount.trim().isEmpty) {
      showToast("金额不能为空");
      return;
    }
    if (double.parse(amount) <= (withdrawConfig.value.minQuota ?? 100)) {
      showToast("金额最低提现100");
      return;
    }

    LoadingView.singleton.wrap(
        context: Get.context!,
        asyncFunction: () async {
          Api.applyWithdrawal(
            money: amount,
            receiptName: name,
            accountNo: account,
            payType: payType.value,
            purType: title.value == "余额" ? 1 : 2,
          ).then((response) {
            if (response) {
              showToast("提交成功");
            }
            Get.back();
          });
        });
  }
}
